package controller

import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"mytest/code"
	"mytest/database"
	"mytest/flower-order/model"
	"mytest/util"
)

type ConfigController struct {
}

func (t *ConfigController) Index(c *gin.Context) {
	var configList []*model.Config
	err := database.DB.Debug().Model(model.Config{}).Find(&configList).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		c.JSON(code.Success, util.ReturnError(code.SysErr, err.Error()))
		return
	}
	data := make(map[string]string)
	for _, v := range configList {
		data[v.Name] = v.Value
	}
	response := util.ReturnSuccess(data)
	c.JSON(code.Success, response)
	return
}

func (t *ConfigController) Edit(c *gin.Context) {
	var paramMap map[string]interface{}
	err := c.BindJSON(&paramMap)
	if err != nil {
		c.JSON(code.Success, util.ReturnError(code.ParamErr, err.Error()))
		return
	}
	if configMap == nil {
		configMap = make(map[string]string)
	}
	var errStrList []string
	for k, v := range paramMap {
		err = database.DB.Debug().Model(&model.Config{}).Where("name = ?", k).Update("value", v).Error
		if err != nil {
			errStrList = append(errStrList, err.Error())
		}
		configMap[k] = v.(string)
	}
	if len(errStrList) > 0 {
		c.JSON(code.Success, util.ReturnError(code.SaveErr, errStrList[0]))
		return
	}
	c.JSON(code.Success, util.ReturnSuccess(nil))
	return
}

func (t *ConfigController) GetConfigByKey(c *gin.Context) {
	if configMap == nil {
		configMap = make(map[string]string)
		var configList []*model.Config
		database.DB.Debug().Model(model.Config{}).Find(&configList)
		for _, v := range configList {
			configMap[v.Name] = v.Value
		}
	}
	response := util.ReturnSuccess(configMap[c.DefaultPostForm("key", "")])
	c.JSON(code.Success, response)
	return
}
